package com.xu.lock;

import java.util.concurrent.atomic.AtomicInteger;

/**
 *TicketLock即为排队自旋锁。思路：类似银行办业务，先取一个号，然后等待叫号叫到自己。
 * 好处：保证FIFO，先取号的肯定先进入。而普通的SpinLock，
 * 大家都在转圈，锁释放后谁刚好转到这谁进入
 * @author xudenghui
 * @create 2023-03-06 10:16
 **/
public class TicketLock {

    /**
     * 服务号
     */
    private AtomicInteger serviceNum = new AtomicInteger();
    /**
     * 排队号
     */
    private AtomicInteger ticketNum = new AtomicInteger();

    public  int lock(){
        int myTicketNum = ticketNum.getAndIncrement();

        while(serviceNum.get() != myTicketNum){

        }
        return  myTicketNum;
    }

    public  void unLock(int myTicketNum){
        int next = myTicketNum = 1;
        serviceNum.compareAndSet(myTicketNum,next);
    }

}
